#include "include/muduo/net/TcpClient.h"
#include "include/muduo/net/EventLoopThread.h"
#include "include/muduo/net/TcpConnection.h"
#include "include/muduo/base/CountDownLatch.h"
#include <iostream>
#include <functional>
#include <unordered_map>

class TranslateClient{
    public:
        TranslateClient(const std::string &sip,int sprot)
            :_latch(1),
             _client(_loopthread.startLoop(),muduo::net::InetAddress(sip,sprot),"TranslateClient"){
                _client.setConnectionCallback(std::bind(&TranslateClient::onConnection,this,std::placeholders::_1));
                _client.setMessageCallback(std::bind(&TranslateClient::onMessage, this, std::placeholders::_1,
        std::placeholders::_2, std::placeholders::_3));
        }
        void connect(){
            //连接
            _client.connect();
            _latch.wait();//阻塞等待，直到连接建立成功
        }
        bool send(const std::string &msg){
            if(_conn->connected())//连接正常再发送
            {
                _conn->send(msg);
                return true;
            }
            return false;
        }
    private:
        //连接建立成功，回调
        void onConnection(const muduo::net::TcpConnectionPtr &conn){
            if(conn->connected()){
                _latch.countDown();//唤醒
                _conn=conn;
            }
            else{
                //连接关闭
            }
        }
        //收到消息时，回调
        void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp){
            std::cout<<"结果："<<buf->retrieveAllAsString()<<std::endl;
        }
    private:
        //同步操作，等连接真正成功后，再发生消息
        muduo::CountDownLatch _latch;
        //clien依赖evloop进行事件监控，但只能在每个线程中进行事件监控
        //否则会阻塞整个进程
        muduo::net::EventLoopThread _loopthread;//二合一
        muduo::net::TcpClient _client;//建立连接后赋值给conn
        //后面的发生操作都交给_conn
        muduo::net::TcpConnectionPtr _conn;
};
int main(){
    TranslateClient client("127.0.0.1",8888);
    client.connect();
    while(1){
        std::string buf;
        std::cin>>buf;
        client.send(buf);
    }
    return 0;
}